package com.example.demo.web.session;

import com.example.demo.car.vo.UserInfo;
import com.example.demo.interceptor.CarInterceptor;
import com.example.demo.utils.SysUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * cookie
 */
@Slf4j
@Controller
@RequestMapping("cookie")
public class CookieController {

    @RequestMapping("add")
    @ResponseBody
    public String login(HttpServletRequest req, HttpServletResponse resp, HttpSession session) {

        String uuid = SysUtils.getUUID();
        Cookie cookie = new Cookie("user-key", SysUtils.getDateStrHms());
        cookie.setMaxAge(30 * 24 * 60 * 60);
        //子域下也可访问
        cookie.setDomain("grq.com");
        cookie.setPath("/");
        resp.addCookie(cookie);
        return String.format("%s|%s|", SysUtils.getDateSpan(), uuid);
    }

    @RequestMapping("get")
    public @ResponseBody
    String getCookie(HttpServletRequest req, HttpServletResponse resp,
                     HttpSession session,
                     @CookieValue(value = "user-key", required = false)
                             String coookieKey) {

        UserInfo userInfo = CarInterceptor.threadLocal.get();

        if (StringUtils.isEmpty(coookieKey)) {
            return String.format("%s||userKey=%s", SysUtils.getDateSpan(),userInfo.getUserKey());
        }
        return String.format("%s|%s|", SysUtils.getDateSpan(), coookieKey);
    }

    @RequestMapping("show")
    public String showCookie(HttpServletRequest req, HttpServletResponse resp, HttpSession session, @CookieValue(value = "user-key", required = false)
            String coookieKey) {
        return "menu/menu";
    }

}
